<?php

/**
 * This is the model class for table "orders".
 *
 * The followings are the available columns in table 'orders':
 * @property string $id
 * @property string $order_number
 * @property string $site_key
 * @property string $total_price
 * @property string $comment
 * @property string $coupon
 * @property string $offset
 * @property string $order_date
 * @property string $pay_status
 * @property string $status
 * @property string $uid
 * @property string $pay_type
 */
class Orders extends CActiveRecord {

    public $orderStatus = array(
        'NW' => 'New',
        'OE' => 'New',
        'NP' => 'Unauthenticated ',
        'DO' => 'Delivery',
        'OP' => 'Validation',
        'OV' => 'Complete',
        'RM' => 'Refund'
    );

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Orders the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'orders';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('pay_type, total_price, order_number', 'required'),
            array('order_number', 'length', 'max' => 20),
            array('total_price, offset', 'length', 'max' => 10),
            array('coupon, pay_type', 'length', 'max' => 50),
            array('order_date, uid', 'length', 'max' => 11),
            array('pay_status, status', 'length', 'max' => 2),
            array('currency_tag', 'length', 'max' => 3),
            array('comment', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, order_number, total_price, comment, coupon, offset, order_date, pay_status, status, uid, pay_type, currency_tag', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'order_number' => 'Order Number',
            'total_price' => 'Total Price',
            'comment' => 'Comment',
            'coupon' => 'Coupon',
            'offset' => 'Offset',
            'order_date' => 'Order Date',
            'pay_status' => 'Pay Status',
            'status' => 'Status',
            'uid' => 'Uid',
            'pay_type' => 'Pay Type',
            'currency_tag' => 'Currency'
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('order_number', $this->order_number);
        $criteria->compare('total_price', $this->total_price, true);
        $criteria->compare('comment', $this->comment, true);
        $criteria->compare('coupon', $this->coupon);
        $criteria->compare('order_date', $this->order_date, true);
        $criteria->compare('pay_status', $this->pay_status);
        $criteria->compare('status', $this->status, true);
        $criteria->compare('uid', $this->uid);
        $criteria->compare('pay_type', $this->pay_type);

        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                ));
    }

    /**
     * 保存订单用户信息到COOKIE
     * @param type $data
     */
    public function saveCustomer($data) {
        $value = base64_encode(serialize($data));
        $cookie = new CHttpCookie('order_customer', $value);
        $cookie->expire = time() + 86400 * 7;
        Yii::app()->request->cookies['order_customer'] = $cookie;
        return true;
    }

    /**
     * 从COOKIE获取订单用户信息到
     * @return array
     */
    public function getCustomer() {
        $cookie = Yii::app()->request->cookies['order_customer'];
        if (!empty($cookie->value)) {
            return unserialize(base64_decode($cookie->value));
        } else {
            if (isset(Yii::app()->request->cookies['member_uid'])) {
                $uid = Yii::app()->request->cookies['member_uid']->value;
                $member = WebCustomers::model()->findByPk($uid);
                return $member->attributes;
            } else {
                return null;
            }
        }
    }

    /**
     * 产品名称和总价
     * @param array $order 产品信息
     * @param array $num 数量
     * @return array|null
     */
    public function getProduct($order = NULL, $num = 1) {
        $product_array = array();
        if ($order) {
            switch ($order['product_type']) {
                case 'GOLD':
                    $gold = ProductGold::model()->findByPk($order['product_id']);
                    $product = $gold->gold_name;
                    $server = ProductCategory::model()->findByPk($order['server_id']);
                    $price = $gold->gold_num * $gold->gold_discount * $server->price;
                    break;
                case 'PL':
                    $product = 'Powerleveling:' . $order['start_level'] . '-' . $order['end_level'];
                    $pl = ProductPowerleveling::model()->getPowerlevelPH($order['game_id'], $order['start_level'], $order['end_level']);
                    $price = $pl->pl_price;
                    break;
                case 'SKILL':
                    $start_level = (int) $order['start_level'];
                    $end_level = (int) $order['end_level'];
                    $skill_id = (int) $order['skill_id'];
                    $skill = ProductSkill::model()->findByPk($skill_id);
                    $attack = (int) $order['attack'];
                    $defence = (int) $order['defence'];
                    $strength = (int) $order['strength'];
                    $parms = array(
                        'game_id' => $order['game_id'],
                        'skill_id' => $skill_id,
                        'start_level' => $start_level,
                        'end_level' => $end_level,
                        'attack' => $attack,
                        'defence' => $defence,
                        'strength' => $strength,
                    );

                    $skilllevel_data = ProductSkill::model()->getSkillLevelPH($parms);
                    $product = $skill->skill_name . ' Powerleveling: ' . $start_level . ' - ' . $end_level;
                    $price = $skilllevel_data->skill_price;
                    break;
                case 'ITEM':
                    $productObj = ProductBase::model()->findByPk($order['product_id']);
                    $nums = $productObj->getNums();
                    $discount = 1; //折扣
                    foreach ($nums['num'] as $key => $v) {
                        if ($v == $num)
                            $discount = $nums['discount'][$key];
                    }
                    $discount = $discount > 1 ? $discount / 100 : $discount;
                    $product = $productObj->p_name;
                    $price = $productObj->p_price * $discount;
                    break;
                default :
                    $productObj = ProductBase::model()->findByPk($order['product_id']);
                    $product = $productObj->p_name;
                    $price = $productObj->p_price * $productObj->p_rebate;
                    break;
            }
            $product_array = array(
                'product_name' => $product,
                'price' => $price * $num,
            );
            return $product_array;
        } else {
            return null;
        }
    }

    /**
     * 计算订单总价, 只按美元计算
     * @return float
     */
    public function totalPrice($orders = NULL) {
        if (empty($orders)) {
            $cart = new Cart();
            $orders = $cart->orders;
        }
        $total_price = 0;
        if (!empty($orders)) {
            foreach ($orders as $order) {
                $product = $this->getProduct($order, $order['num']);
                $total_price += $product['price'];
            }
            return $total_price;
        } else {
            return 0;
        }
    }

    /**
     * 计算优惠金额
     * @param string $coupon
     * @return float
     */
    public function getOffset($coupon, $price=0) {
        if (WebCoupon::model()->checkCoupon($coupon)) {
            $couponData = WebCoupon::model()->findByAttributes(array(
                'coupon' => $coupon,
                    ));
            //print_r($couponData->attributes);

            $cart = new Cart();
            $orders = $cart->orders;
            $offset = 0;
            if (!empty($orders)) {
                //echo 111;
                foreach ($orders as $order) {
                    if ( (($couponData->product_type == 'ALL' || $couponData->product_type == $order['product_type']) && ($couponData->game_id == 0 || $couponData->game_id == $order['game_id'])) && ($couponData->min_money == 0 || $couponData->min_money >= $price) ) {
                        //echo $price;
                        
                        switch ($couponData->coupon_type) {
                            case 'percent':
                                $product = $this->getProduct($order, $order['num']);
                                $price = $product['price'];
                                if ($couponData->coupon_value > 1) {
                                    $offset += $price * (1-$couponData->coupon_value / 100);
                                } else {
                                    $offset += $price * ( 1- $couponData->coupon_value);
                                }
                                break;
                            case 'offset':
                                $offset += $couponData->coupon_value;
                                break;
                        }
                    }
                }
                return round($offset, 2);
            } else {
                return 0;
            }
        } else {
            return 0;
        }
    }

    /**
     * 生成订单号
     * @param string $game_alias
     * @return string 
     */
    public function generateOrderNumber() {
        $order_prefix = WebOption::model()->getOrderPrefix();
        return strtoupper($order_prefix) . date('ymd') . sprintf('%04d', rand(1, 9999));
    }

    /**
     * 更新订单支付信息
     * @param type $orderNumber
     * @param type $payData
     * @return type 
     */
    public function updateOrderPay($orderNumber, $payData) {
        $pModel = new OrdersPaypal;
        $paypal = $pModel->findByAttributes(array(
            'order_number' => $orderNumber,
                ));
        if ($paypal) {
            $pModel = $pModel->findByPk($paypal->id);
        }
        $pModel->attributes = $payData;
        $pModel->order_number = $orderNumber;
        $pModel->pay_type = 'PayPal';
        $payStatus = '';
        switch ($payData['payment_status']) {
            case 'Refunded':
                $payStatus = 'RP';
                break;
            case 'Completed':
                $payStatus = 'PY';
                break;
        }

        $this->updatePayStatus($orderNumber, $payStatus);
        return $pModel->save();
    }

    /**
     * 更新订单支付状态
     */
    public function updatePayStatus($orderNumber, $payStatus) {
        $order = $this->findByAttributes(array(
            'order_number' => $orderNumber,
                ));
        return $this->updateByPk($order->id, array(
                    'pay_status' => $payStatus,
                ));
    }

    /**
     * 获取订单详情包括支付信息
     * @param type $orderNumber
     * @return type 
     */
    public function getOrderByNumberAll($orderNumber) {
        $order = array(
            'base' => array(),
            'customer' => array(),
            'payment' => array(),
            'items' => array(),
        );
        $order['base'] = $this->findByAttributes(array('order_number' => $orderNumber))->attributes;
        $order['base']['all_money'] = $order['base']['total_price'];
        //来源网站
        $order['base']['from_web'] = Yii::app()->params['domain'];
        $order['customer'] = OrdersCustomer::model()->findByAttributes(array('order_number' => $orderNumber))->attributes;
        $order['payment'] = OrdersPaypal::model()->findByAttributes(array('order_number' => $orderNumber))->attributes;

        $items = OrdersItems::model()->findAllByAttributes(array(
            'order_number' => $orderNumber,
                ));
        foreach ($items as $item) {
            $v = $item->attributes;
            $v['input'] = unserialize($v['input']);
            $order['items'][] = $v;
        }
        return $order;
    }

    /**
     * 设置订单用户ID
     */
    public function beforeSave() {
        parent::beforeSave();
        $uid = (int) Yii::app()->request->cookies['member_uid']->value;
        $this->uid = $uid;
        return true;
    }

}